<!DOCTYPE html>
<html>
<head>
    <style>
        .container { padding: 20px; }
        .string-display {
            display: flex;
            margin: 20px 0;
            font-family: monospace;
        }
        .char-box {
            width: 40px;
            height: 40px;
            border: 1px solid #ccc;
            display: flex;
            align-items: center;
            justify-content: center;
            margin-right: 5px;
        }
        .window-highlight {
            background-color: #e3f2fd;
        }
        .counters {
            display: flex;
            gap: 20px;
            margin: 20px 0;
        }
        .counter-table {
            border-collapse: collapse;
        }
        .counter-table td {
            border: 1px solid #ddd;
            padding: 8px;
            text-align: center;
        }
        .highlight { background-color: #c8e6c9; }
        .negative { background-color: #ffcdd2; }
        button { margin: 10px; padding: 5px 15px; }
    </style>
</head>
<body>
    <div class="container">
        <h3>滑动窗口动画演示：s="cbaebabacd", p="abc"</h3>

        <!-- 字符串展示 -->
        <div id="stringDisplay" class="string-display"></div>

        <!-- 计数器展示 -->
        <div class="counters">
            <div>
                <div>窗口字符计数：</div>
                <table id="sCount" class="counter-table"></table>
            </div>
            <div>
                <div>目标计数(p)：</div>
                <table id="pCount" class="counter-table"></table>
            </div>
        </div>

        <!-- 结果展示 -->
        <div>找到的索引：<span id="result"></span></div>

        <!-- 控制按钮 -->
        <button onclick="startAnimation()">开始</button>
        <button onclick="pauseAnimation()">暂停</button>
        <button onclick="resetAnimation()">重置</button>
    </div>

    <script>
        // 初始化数据
        const s = "cbaebabacd";
        const p = "abc";
        let currentIndex = 0;
        let animationSpeed = 1000; // 每个步骤间隔1秒(1000ms)
        let animationTimer = null; // 改用setInterval控制
        let pCount = new Array(26).fill(0);
        let sCount = new Array(26).fill(0);

        // 初始化显示
        function initDisplay() {
            const stringDisplay = document.getElementById('stringDisplay');
            stringDisplay.innerHTML = s.split('').map((c, i) =>
                `<div class="char-box" id="char${i}">${c}</div>`
            ).join('');

            // 初始化计数表
            initCounterTable('pCount', pCount);
            initCounterTable('sCount', sCount);
        }

        // 初始化计数表
        function initCounterTable(id, counts) {
            const table = document.getElementById(id);
            let html = '<tr>';
            for (let i = 0; i < 26; i++) {
                const char = String.fromCharCode(97 + i);
                html += `<td>${char}<br><span id="${id}_${char}">0</span></td>`;
            }
            table.innerHTML = html + '</tr>';
        }

        // 更新计数显示
        function updateCounter(id, counts) {
            counts.forEach((count, i) => {
                const char = String.fromCharCode(97 + i);
                const elem = document.getElementById(`${id}_${char}`);
                elem.textContent = count;
                elem.parentElement.classList.remove('highlight', 'negative');
                if (count > parseInt(elem.dataset.prev || 0)) {
                    elem.parentElement.classList.add('highlight');
                } else if (count < parseInt(elem.dataset.prev || 0)) {
                    elem.parentElement.classList.add('negative');
                }
                elem.dataset.prev = count;
            });
        }

        // 动画步骤
        function animationStep() {
            if (currentIndex >= s.length - p.length + 1) {
                clearInterval(animationTimer);
                return;
            }

            // 更新窗口高亮
            document.querySelectorAll('.char-box').forEach((box, i) => {
                box.classList.toggle('window-highlight',
                    i >= currentIndex && i < currentIndex + p.length);
            });

            // 更新计数
            if (currentIndex === 0) {
                // 初始窗口
                for (let i = 0; i < p.length; i++) {
                    const charCode = s.charCodeAt(i) - 97;
                    sCount[charCode]++;
                }
                p.split('').forEach(c => pCount[c.charCodeAt(0)-97]++);
            } else {
                // 滑动窗口
                const removeChar = s[currentIndex - 1];
                sCount[removeChar.charCodeAt(0)-97]--;

                const addChar = s[currentIndex + p.length - 1];
                sCount[addChar.charCodeAt(0)-97]++;
            }

            // 更新显示
            updateCounter('sCount', sCount);
            updateCounter('pCount', pCount);

            // 检查匹配
            if (JSON.stringify(sCount) === JSON.stringify(pCount)) {
                document.getElementById('result').textContent += ` ${currentIndex}`;
            }

            currentIndex++;
        }

        // 控制函数
        function startAnimation() {
            if (!animationTimer) {
                animationStep(); // 立即执行第一步
                animationTimer = setInterval(animationStep, animationSpeed);
            }
        }

        function pauseAnimation() {
            clearInterval(animationTimer);
            animationTimer = null;
        }

        function resetAnimation() {
            pauseAnimation();
            currentIndex = 0;
            pCount.fill(0);
            sCount.fill(0);
            document.getElementById('result').textContent = '';
            initDisplay();
        }

        // 初始化
        initDisplay();
    </script>
</body>
</html>
